import xbmc, xbmcgui, xbmcaddon, xbmcplugin
import urllib, urllib2
import re, string, sys, os
import urlresolver
from t0mm0.common.addon import Addon
from t0mm0.common.net import Net
import HTMLParser

try:
	from sqlite3 import dbapi2 as sqlite
	print "Loading sqlite3 as DB engine"
except:
	from pysqlite2 import dbapi2 as sqlite
	print "Loading pysqlite2 as DB engine"

addon_id = 'plugin.video.desirulez'
plugin = xbmcaddon.Addon(id=addon_id)

DB = os.path.join(xbmc.translatePath("special://database"), 'desirulez.db')
BASE_URL = 'http://www.desirulez.net'
net = Net()
addon = Addon('plugin.video.desirulez', sys.argv)
showAllParts = True
showPlayAll = True

if plugin.getSetting('showAllParts') == 'false':
        showAllParts = False

if plugin.getSetting('showPlayAll') == 'false':
        showPlayAll = False

##### Queries ##########
mode = addon.queries['mode']
url = addon.queries.get('url', None)
content = addon.queries.get('content', None)
query = addon.queries.get('query', None)
startPage = addon.queries.get(
'startPage', None)
numOfPages = addon.queries.get('numOfPages', None)
listitem = addon.queries.get('listitem', None)
urlList = addon.queries.get('urlList', None)


SITES_1 =  ['xpressvids.info', 'bollylinks.info','atozdesi.info', 'desivid.net23.net']
SITES_2 =  ['desiupdate.info', 'bollymoviz.com', 'videos.desihome.info', 'hd-share.info', 'movierulez.in', 'dohori-sanjh.com']
SITES_3 =  ['orphaninneeds.com', 'worldsecurityco.com', 'allvideotv.info', 'estates4u.co', 'priyankhd.in']



def GetTitles(url, startPage= '1', numOfPages= '1'): # Get Movie Titles
        print 'desirulez get Movie Titles Menu %s' % url

        # handle paging
        pageUrl = url
        if int(startPage)> 1:
                pageUrl = url + '-' + startPage + '.html'
        print pageUrl
        html = net.http_GET(pageUrl).content

        start = int(startPage)
        end = start + int(numOfPages)
        
        last = 2
        match  = re.search('class="first_last".+?-([\d]+).html', html)
        if match:
                last = int(match.group(1))

        # Get the sticky section only once
        if start == 1:
                match = re.compile('Sticky:.+?href="(.+?)".+?>(.+?)<', re.DOTALL).findall(html)
                for movieUrl, name in match:
                        cm  = []
                        r = re.search('([\w\s]+)', name)
                        if r:
                                title = r.group(1)
                        else:
                                title = name
                        runstring = 'XBMC.Container.Update(plugin://plugin.video.desirulez/?mode=Search&query=%s)' %(title)
        		cm.append(('Search on Desirulez', runstring))
                        addon.add_directory({'mode': 'GetLinks', 'url': movieUrl}, {'title':  name}, contextmenu_items= cm)   

        print str(start) + ' : ' + str(end) + ' : ' + str(last)
        for page in range( start, min(last, end)):
                if ( page != start):
                        pageUrl = url + '-' + str(page) + '.html'
                        html = net.http_GET(pageUrl).content
                        
                match = re.compile('nonsticky.+?<a class=".+?" href="(.+?)".+?>(.+?)<', re.DOTALL).findall(html)
                for movieUrl, name in match:
                        cm  = []
                        title = name.partition(' ')
                        runstring = 'XBMC.Container.Update(plugin://plugin.video.desirulez/?mode=Search&query=%s)' %(title[0])
        		cm.append(('Search on Desirulez', runstring))
                        addon.add_directory({'mode': 'GetLinks', 'url': movieUrl}, {'title':  name}, contextmenu_items= cm) 

        # keep iterating until the laast page is reached
        if end < last:
                addon.add_directory({'mode': 'GetTitles', 'url': url, 'startPage': str(end), 'numOfPages': numOfPages}, {'title': 'Next...'})

       	xbmcplugin.endOfDirectory(int(sys.argv[1]))


def GetLinks(url): # Get Links
        print '***************************************************** In GetLinks %s' % url
        html = net.http_GET(url).content
        listitem = GetMediaInfo(html)
        
        match = re.compile('<pre class="bbcode_code"style="height:(.+?)</div>', re.DOTALL).findall(html)
        for data in match:
                urlList = []             
                links = re.compile('http(.+?)(?:\n|<|")').findall(data)
                firstPart = True
                print '******************************************************'
                for url in links:

                        if 'http' not in url:
                                url = 'http' + url
                        print url
                        url = url.replace(' ', '')
                        host = GetDomain(url)

                        # Get all mirrors for mirorii.com and it it to links
                        if 'mirorii.com' in url:
                                links.extend(GetMirroriLinks(url))
                                continue
                        if 'multiup.org' in url:
                                links.extend(GetMultiup(url))
                                continue
                        
                        # ignore .rar files
                        r = re.search('\.rar[(?:\.html|\.htm)]*', url, re.IGNORECASE)
                        if r:
                                print 'ignored desirulez url %s' % url
                                continue

                        # ignore .srt files
                        r = re.search('\.srt[(?:\.html|\.htm)]*$', url, re.IGNORECASE)
                        if r:
                                print 'ignored desirulez url %s' % url
                                continue
                        
                        # find parts and build array for plalist
                        r = re.search('\.[0]+([\d]+)[\.]*[(?:html|htm)]*', url, re.IGNORECASE)
                        if r:
                                print 'its a part file'
                                partNum = r.group(1)
                                if firstPart:
                                        print 'in First part'
                                        if len(urlList) > 0:
                                                if showPlayAll and urlresolver.HostedMediaFile(url= urlList[0]):
                                                        print 'adding previous parts'
                                                        title =  GetDomain(urlList[0]) + ' : Play All ' + str(len(urlList)) + ' Parts'
                                                        addon.add_directory({'mode': 'PlayVideo', 'urlList': SortUrlList(urlList), 'listitem': listitem}, {'title': title })
                                                        
                                        urlList = []
                                        firstPart = False
                                urlList.append(url)
                                if showAllParts and urlresolver.HostedMediaFile(url= url):
                                        title = url.rpartition('/')
                                        title = title[2].replace('.html', '')
                                        title = title.replace('.htm', '')
                                        title = GetDomain(url) + ' : ' + title
                                        addon.add_directory({'mode': 'PlayVideo', 'urlList': [url], 'listitem': listitem}, {'title': title })
                                continue
                        else:
                                print 'its a single file'
                                if len(urlList) > 0:
                                        print 'adding previous parts'
                                        if showPlayAll and urlresolver.HostedMediaFile(url= urlList[0]):
                                                print 'adding previous parts'
                                                title =  GetDomain(urlList[0]) + ' : Play All ' + str(len(urlList)) + ' Parts'
                                                addon.add_directory({'mode': 'PlayVideo', 'urlList': urlList, 'listitem': listitem}, {'title': title })
                                print 'single file link'
                                # if its a single link just build array of just that link
                                urlList = []
                                urlList.append(url)
                        
                                if urlresolver.HostedMediaFile(url= urlList[0]):
                                        host = host + ' : Single link'
                                        addon.add_directory({'mode': 'PlayVideo', 'urlList': urlList, 'listitem': listitem}, {'title':  host})
                                        urlList = []
                if len(urlList) > 0:
                        if showPlayAll and urlresolver.HostedMediaFile(url= urlList[0]):
                                title =  GetDomain(urlList[0]) + ' : Play All ' + str(len(urlList)) + ' Parts'
                                addon.add_directory({'mode': 'PlayVideo', 'urlList': SortUrlList(urlList), 'listitem': listitem}, {'title': title })
                                urlList = []

        match = re.compile('<a onclick=".+?" href="(.+?)".+?">(.+?)<', re.DOTALL).findall(html)
        urlList = []
        for url, name in match:

                host = GetDomain(url)

                #ignore unknown hosts
                if 'Unknown' in host:
                        continue
                # Resolve links if its a known Desirulez mirror
                if any(host in s for s in SITES_1) or any(host in s for s in SITES_2) or any(host in s for s in SITES_3) :
                        url = GetVideoLinks(host, url)
                        host = GetDomain(url)

                print '##################################### %s %s' %(url, name)
                # ignore .rar files
                # \.rar[(?:\.html$|\.htm$)]+
                r = re.search('\.rar[(?:\.html|\.htm)]*', url, re.IGNORECASE)
                if r:
                        print 'ignored desirulez url %s' % url
                        continue

                # find parts and build array for plalist
                print ' ------------------Name is %s----' % name
                r = re.search('Part?.([\d]+)[\s]*', name,  re.IGNORECASE)
                if r:
                        print 'found parts'
                        partNum = r.group(1)
                        if int(partNum.strip()) == 1:
                                print 'in First part'
                                if len(urlList) > 0:
                                        if showPlayAll and urlresolver.HostedMediaFile(url= urlList[0]):
                                                print 'in parts : adding previous parts %d' % len(urlList)
                                                title =  GetDomain(urlList[0]) + ' : Play All ' + str(len(urlList)) + ' Parts'
                                                addon.add_directory({'mode': 'PlayVideo', 'urlList': urlList, 'listitem': listitem}, {'title': title })
                                urlList = []
                        urlList.append(url)
                        if showAllParts and urlresolver.HostedMediaFile(url= url):
                                title =  GetDomain(url) + ' : Part ' + partNum
                                addon.add_directory({'mode': 'PlayVideo', 'urlList': [ url ], 'listitem': listitem}, {'title': title}) 
                        continue
                else:
                        if len(urlList) > 0:
                                if showPlayAll and urlresolver.HostedMediaFile(url= urlList[0]):
                                        print 'in single : adding previous parts %d' % len(urlList)
                                        title =  GetDomain(urlList[0]) + ' : Play All ' + str(len(urlList)) + ' Parts'
                                        addon.add_directory({'mode': 'PlayVideo', 'urlList': urlList, 'listitem': listitem}, {'title': title })
                        print 'single file link'
                        # if its a single link just build array of just that link
                        urlList = []
                        urlList.append(url)
                
                        if urlresolver.HostedMediaFile(url= urlList[0]):
                                host = host + ' : Single link'
                                addon.add_directory({'mode': 'PlayVideo', 'urlList': urlList, 'listitem': listitem}, {'title':  host})
                                urlList = []

        if len(urlList) > 0:
                if showPlayAll and urlresolver.HostedMediaFile(url= urlList[0]):
                        title =  GetDomain(urlList[0]) + ' : Play All ' + str(len(urlList)) + ' Parts'
                        addon.add_directory({'mode': 'PlayVideo', 'urlList': urlList, 'listitem': listitem}, {'title': title })
        
        xbmcplugin.endOfDirectory(int(sys.argv[1]))

def SortUrlList(urlList):
        print 'In SortUrlList'
        retList = [''] * len(urlList)
        for url in urlList:
                partNum = re.search('\.[0]+([\d]+)[\.]*[(?:html|htm)]*', url, re.IGNORECASE).group(1)
                retList[int(partNum) - 1] = url
        print retList
        return retList

def GetVideoLinks(host, url):
        if any(host in s for s in SITES_1):
                links = re.compile('<embed src="(.+?)"').findall(net.http_GET(url).content)
                if len(links):
                        return links[0]        
        if any(host in s for s in SITES_1):
                links = re.compile('<iframe src="(.+?)"', re.IGNORECASE).findall(net.http_GET(url).content)
                if len(links):
                        return links[0]
        if any(host in s for s in SITES_1):
                links = re.compile('object.+?value="(.+?)"').findall(net.http_GET(url).content)
                if len(links):
                        return links[0]
        if any(host in s for s in SITES_2):
                links = re.compile('object.+?src="(.+?)"').findall(net.http_GET(url).content)
                if len(links):
                        return links[0]
        if any(host in s for s in SITES_2):
                links = re.compile('object.+?value="(.+?)"').findall(net.http_GET(url).content)
                if len(links):
                        return links[0]
        if any(host in s for s in SITES_3):
                links = re.compile('<iframe src="(.+?)"', re.IGNORECASE).findall(net.http_GET(url).content)
                if len(links):
                        return links[0]
        if any(host in s for s in SITES_2):
                links = re.compile('name="movie" value="(.+?)"').findall(net.http_GET(url).content)
                if len(links):
                        return links[0]
        #print 'ignored desirulez url %s' % url
        return url

def GetMirroriLinks(url):
        html = net.http_GET(url).content
        match = re.compile('<li id=".+?".+?href="(.+?)"').findall(html)
        return match

def GetMultiup(url):
        html = net.http_GET(url).content
        form_values = {}
        for i in re.finditer('<input type="hidden" name="(.+?)" value="(.+?)"', html):
            form_values[i.group(1)] = i.group(2)
        r = re.search('What is the result of ([\d]+) \+ ([\d]+)', html)
        if not r:
                print 'could not find security code'
                return []
        form_values["data[Fichier][security_code]"] = str(int(r.group(1)) + int(r.group(2)))
        html = net.http_POST(url, form_data=form_values).content
        match = re.compile('href="(.+?)">Download').findall(html)
        return match


def PlayVideo(urlList, listitem):
        print '************************************* in PlayVideo'
        print urlList
        
        playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
	playlist.clear()
	urlList = map(str, urlList[1:-1].split(','))
	try:
                for url in urlList:
                        url = url.replace('\\r', '').replace("u'", "").replace("'", "").strip()
                        print 'url is %s' % url
                        playlist.add(url= urlresolver.HostedMediaFile(url).resolve())
                xbmc.Player().play(playlist)
        except:
                print 'error while trying to PlayVideo'

def GetDomain(url):
        tmp = re.compile('//(.+?)/').findall(url)
        domain = 'Unknown'
        if len(tmp) > 0 :
            domain = tmp[0].replace('www.', '')
        return domain


def GetMediaInfo(html):
        listitem = xbmcgui.ListItem()
        match = re.search('og:title" content="(.+?) \((.+?)\)', html)
        if match:
                print match.group(1) + ' : '  + match.group(2)
                listitem.setInfo('video', {'Title': match.group(1), 'Year': int(match.group(2)) } )
        return listitem

def MainMenu():  #homescreen

        addon.add_directory({'mode': 'Sab'}, {'title': 'SAB'})  
        addon.add_directory({'mode': 'Sony'}, {'title': 'SONY'})   
        addon.add_directory({'mode': 'Colors'}, {'title': 'COLORS'}) 
        addon.add_directory({'mode': 'starplus'}, {'title': 'STAR PLUS'})  
        addon.add_directory({'mode': 'zeetv'}, {'title': 'ZEE TV'})   
        addon.add_directory({'mode': 'lifeok'}, {'title': 'LIFE OK'}) 
        addon.add_directory({'mode': 'ndtvimagine'}, {'title': 'NDTV IMAGINE'})     
        addon.add_directory({'mode': 'Hindi'}, {'title': 'Hindi Movies'})      
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/punjabi-movies/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'Punjabi Movies - Desirulez'}) 
        addon.add_directory({'mode': 'GetSearchQuery'},  {'title':  'Search'})
        addon.add_directory({'mode': 'ResolverSettings'}, {'title':  'Resolver Settings'})
        xbmcplugin.endOfDirectory(int(sys.argv[1]))

def Sab():
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/taarak-mehta-ka-ooltah-chashmah/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'TARAK MEHTA KA OOLTAH CHASHMAH'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/r-k-laxman-ki-duniya/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'R.K. LAKSHMAN'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/lapata-ganj/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'LAPATAGANJ'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/bhai-bhaiya-aur-brother/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'BHAI BHAIYA AUR BROTHER'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/chidiya-ghar/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'CHIDIYA GHAR'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/fir/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'FIR'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/movers-shakers/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'MOVERS AND SHAKERS'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/gopi-gadha-aur-gupshup/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'GOPI GADHA AUR GUPSHUP'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/gutur-gu/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'GUTUR GU'}) 
        xbmcplugin.endOfDirectory(int(sys.argv[1]))

def Sony():
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/indian-idol-6/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'INDIAN IDOL 6'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/crime-patrol-season-4/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'CRIME PATROL DASTAK 4'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/c-i-d/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'C.I.D.'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/adaalat/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'ADAALAT'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/bade-acche-lagte-hai/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'BADE ACCHE LAGTE HAI'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/kahani-comedy-circus-ki/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'KAHANI COMEDY CIRCUS KI'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/shubh-vivah/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'SHUBH VIVAH'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/byah-hamari-bahu-ka/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'BYAH HAMARI BAHU KA'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/dekha-ek-khwaab/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'DEKHA EK KHWAAB'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/saas-bina-sasural/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'SAAS BINA SASURAL'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/parvarrish/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'PARVARRISH'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/kya-hua-tera-vaada/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'KYA HUA TERA VAADA'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/kuch-toh-log-kahenge/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'KUCH TOH LOG KAHENGE'})
        xbmcplugin.endOfDirectory(int(sys.argv[1]))
       
def Colors():
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/balika-vadhu/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'BALIKA VADHU'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/na-aana-iss-desh-laado/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'NA AANA ISS DESH LAADO'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/kairi/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'KAIRI'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/sasural-simar-ka/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'SASURAL SIMAR KA'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/madhubala-ek-ishq-ek-junoon/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'MADHUBALA EK ISHQ EK JUNOON'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/chal-sheh-aur-maat/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'CHAL SHEH AUR MAAT'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/parichay/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'PARICHAY'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/uttaran/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'UTTARAN'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/na-bole-tum-na-maine-kuch-kaha/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'NA BOLE TUM NA MAINE KUCH KAHA'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/jhalak-dikhla-ja-season-5/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'JHALAK DIKHLA JA SEASON 5'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/zindagi-ki-haqeeqat-se-aamna-saamna-season-2/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'ZINDAGI KI HAQEEQAT SE AAMNA SAAMNA SEASON 2'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/late-night-show-jitna-rangeen-utna-sangeen/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'LATE NIGHT SHOW JITNA RANGEEN UTNA SANGEEN'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/all-well/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'ALL WELL'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/jai-shri-krishna/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'JAI SHRI KRISHNA'})
        xbmcplugin.endOfDirectory(int(sys.argv[1]))

def starplus():
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/satyamev-jayate/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'SATYAMEY JAYATE'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/gumrah/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'GUMRAH'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/pratigya/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'PRATIGYA'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/pyaar-ka-dard-meetha-meetha-pyara-pyara/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'PYAAR KA DARD MEETHA MEETHA PYARA - PYARA'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/yeh-rishta-kya-kehlata-hai/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'YEH RISHTA KYA KEHLATA HAI'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/diya-aur-baati-hum/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'DIYA AUR BAATI HUM'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/ek-hazaaron-mein-meri-behna-hain/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'EK HAZAARON MEIN MERI BEHNA HAIN'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/iss-pyaar-ko-kya-naam-doon/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'ISS PYAAR KO KYA NAAM DOON'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/ek-doosre-se-karte-hai-pyaar-hum/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'EK DOOSRE SE KARTE HAI PYAAR HUM'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/saath-nibhana-saathiya/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'SAATH NIBHANA SAATHIYA'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/ruk-jana-nahi/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'RUK JANA NAHI'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/front-row-star-world/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'FRONT ROW STAR WORLD'})
        xbmcplugin.endOfDirectory(int(sys.argv[1]))

def zeetv():
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/afsar-bitiya/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'AFSAR BITIYA'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/sapne-suhane-ladakpan-ke/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'SAPNE SUHANE LADAKPAN KE'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/rab-se-sona-ishq/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'RAB SE SONA ISHQ'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/hitler-didi/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'HITLER DIDI'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/yahan-main-ghar-ghar-kheli/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'YAHAN MAIN GHAR GHAR KHELI'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/pavitra-rishta/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'PAVITRA RISHTA'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/phir-subah-hogi/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'PHIR SUBAH HOGI'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/mrs-kaushik-ki-paanch-bahuein/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'MRS. KAUSHIK KI PAANCH BAHUEIN'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/punar-vivah/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'PUNAR VIVAH'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/dance-india-dance-little-masters-2012/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'DANCE INDIA DANCE LITTLE MASTERS 2012'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/fear-files-dar-ki-sacchi-tasveerein/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'FEAR FILES DAR KI SACCHI TASVEEREIN'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/aapka-sapna-hamara-apna/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'AAPKA SAPNA HAMARA APNA'})
        xbmcplugin.endOfDirectory(int(sys.argv[1]))

def lifeok():
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/devon-ke-dev-mahadev/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'DEVON KE DEV MAHADEV'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/amrit-manthan/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'AMRIT MANTHAN'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/sapno-ke-bhanwar-mein/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'SAPNO KE BHANWAR MEIN'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/alakshmi/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'ALAKSHMI'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/main-laxmi-tere-aangan-ki/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'MAIN LAXMI TERE AANGAN KI'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/dil-se-di-dua-saubhagyavati-bhava/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'DIL SE DI DUA SAUBHAGYAVATI BAHVA'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/aasman-se-aage/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'AASMAN SE AAGE'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/savdhaan-india-11-crime-alert/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'SAVDHAAN INDIA 11 CRIME ALERT'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/hum-ne-li-hai-shapath/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'HUM NE LI HAI SHAPATH'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/laugh-india-laugh/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'LAUGH INDIA LAUGH'})
        xbmcplugin.endOfDirectory(int(sys.argv[1]))

def ndtvimagine():
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/swayamvar-season-4-veena-ka-vivaah/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'SAWYAMVAR SEASON 4 VEENA KA VIVAAH'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/jamuna-paar/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'JAMUNA PAAR'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/gyaan-guru/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'GYAAN GURU'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/dwarkadheesh/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'DWARKADEHEESH'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/preeto/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'PREETO'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/beendh-banunga-ghodi-chadhunga/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'BEENDH BANUNGA GHODI CHADHUNGA'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/mi-aaji-aur-saheb/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'MI AAJI AUR SAHEB'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/baba-aiso-var-dhoondo/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'BABA AISO VAR DHOONDO'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/haar-jeet/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'HAAR JEET'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/chandragupta-maurya/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'CHANRAGUPTA MAURYA'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/mahima-shani-dev-ki/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'MAHIMA SHANI DEV KI'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/gajab-desh-ki-ajab-kahaaniyan/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'GAJAB DESH KI AJAB KAHAANIYAN'})
        xbmcplugin.endOfDirectory(int(sys.argv[1]))

def Hindi():
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/latest-exclusive-movie-hq/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'Latest High Quality'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/bluray-dvd-english-subs-online/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'High quality/Blueray Movies'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/2010-2011-online/', 'startPage': '1', 'numOfPages': '1'}, {'title': '2010 - 2011 Movies'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/2008-2009-online/', 'startPage': '1', 'numOfPages': '1'}, {'title': '2008 - 2009 Movies'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/2006-2007-online/', 'startPage': '1', 'numOfPages': '1'}, {'title': '2006 - 2007 Movies'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/2005-earlier/', 'startPage': '1', 'numOfPages': '1'}, {'title': '2005 and Earlier'})
        addon.add_directory({'mode': 'GetTitles', 'url': BASE_URL + '/veoh-movies/', 'startPage': '1', 'numOfPages': '1'}, {'title': 'Veoh Movies'})
        xbmcplugin.endOfDirectory(int(sys.argv[1]))

def GetSearchQuery():
	last_search = addon.load_data('search')
	if not last_search: last_search = ''
	keyboard = xbmc.Keyboard()
        keyboard.setHeading('Search TV Shows')
	keyboard.setDefault(last_search)
	keyboard.doModal()
	if (keyboard.isConfirmed()):
                query = keyboard.getText()
                addon.save_data('search',query)
                Search(query)
	else:
                return

        
def Search(query):
        url = 'http://www.google.com/search?q=site:desirulez.net ' + query
        url = url.replace(' ', '+')
        print url
        html = net.http_GET(url).content
        match = re.compile('<h3 class="r"><a href="(.+?)".+?onmousedown=".+?">(.+?)</a>').findall(html)
        for url, title in match:
                title = title.replace('<b>...</b>', '').replace('<em>', '').replace('</em>', '')
                addon.add_directory({'mode': 'GetLinks', 'url': url}, {'title':  title})
	xbmcplugin.endOfDirectory(int(sys.argv[1]))


if mode == 'main': 
	MainMenu()
elif mode == 'GetTitles': 
	GetTitles(url, startPage, numOfPages)
elif mode == 'GetLinks':
	GetLinks(url)
elif mode == 'GetSearchQuery':
	GetSearchQuery()
elif mode == 'Search':
	Search(query)
elif mode == 'PlayVideo':
	PlayVideo(urlList, listitem)	
elif mode == 'ResolverSettings':
        urlresolver.display_settings()
elif mode == 'Sab':
        Sab()
elif mode == 'Sony':
        Sony()
elif mode == 'Colors':
        Colors()
elif mode == 'starplus':
        starplus()
elif mode == 'zeetv':
        zeetv()
elif mode == 'lifeok':
        lifeok()
elif mode == 'ndtvimagine':
        ndtvimagine()
elif mode == 'Hindi':
        Hindi()